package com.emm.yixun.website.service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.emm.yixun.website.constant.PmoConfig;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.bpmn.model.StartEvent;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.enums.ProcessTypeEnums;
import com.emm.yixun.common.model.NodeUser;
import com.emm.yixun.common.model.ProjectProcdef;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.NodeUserDto;
import com.emm.yixun.common.model.dto.ProjectProcdefDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.SendMessageServiceFacade;
import com.emm.yixun.estate.service.ProjectProcdefServiceFacade;
import com.emm.yixun.system.service.BusinessLogServiceFacade;
import com.emm.yixun.system.service.NodeUserServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.service.ao.DataService.OaSendHttpMessageService;
import com.emm.yixun.website.vo.process.ProcessScheduleVo;

/**
 * 流程操作核心类<br>
 * 此核心类主要处理：流程通过、驳回、转办、中止、挂起等核心操作<br>
 * 
 * 
 */
@Service("activitiProcessServiceImpl")
public class ActivitiProcessServiceImpl {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private PmoConfig pmoConfig;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private NodeUserServiceFacade nodeUserServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private SendMessageServiceFacade sendMessageServiceFacade;
	@Autowired
	private ProjectProcdefServiceFacade projectProcdefServiceFacade;
	@Autowired
	private OaSendHttpMessageService oaSendHttpMessageService;
	@Autowired
	private BusinessLogServiceFacade businessLogServiceFacade;

	/**
	 * 驳回流程
	 * 
	 * @param taskId
	 *            当前任务ID
	 * @param activityId
	 *            驳回节点ID
	 * @param variables
	 *            流程存储参数
	 * @throws Exception
	 */
	public void backProcess(String taskId, String activityId, Map<String, Object> variables) throws Exception {
		if (StringUtils.isEmpty(activityId)) {
			throw new Exception("驳回目标节点ID为空！");
		}

		// 查找所有并行任务节点，同时驳回
		List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId(taskId).getId(),
				findTaskById(taskId).getTaskDefinitionKey());
		for (Task task : taskList) {
			commitProcess(task.getId(), variables, activityId);
		}
	}

	/**
	 * 取回流程
	 * 
	 * @param taskId
	 *            当前任务ID
	 * @param activityId
	 *            取回节点ID
	 * @throws Exception
	 */
	public void callBackProcess(String taskId, String activityId) throws Exception {
		if (StringUtils.isEmpty(activityId)) {
			throw new Exception("目标节点ID为空！");
		}

		// 查找所有并行任务节点，同时取回
		List<Task> taskList = findTaskListByKey(findProcessInstanceByTaskId(taskId).getId(),
				findTaskById(taskId).getTaskDefinitionKey());
		for (Task task : taskList) {
			commitProcess(task.getId(), null, activityId);
		}
	}

	/**
	 * 清空指定活动节点流向
	 * 
	 * @param activityImpl
	 *            活动节点
	 * @return 节点流向集合
	 */
	private List<PvmTransition> clearTransition(ActivityImpl activityImpl) {
		// 存储当前节点所有流向临时变量
		List<PvmTransition> oriPvmTransitionList = new ArrayList<PvmTransition>();
		// 获取当前节点所有流向，存储到临时变量，然后清空
		List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
		for (PvmTransition pvmTransition : pvmTransitionList) {
			oriPvmTransitionList.add(pvmTransition);
		}
		pvmTransitionList.clear();

		return oriPvmTransitionList;
	}

	/**
	 * @param taskId
	 *            当前任务ID
	 * @param variables
	 *            流程变量
	 * @param activityId
	 *            流程转向执行任务节点ID<br>
	 *            此参数为空，默认为提交操作
	 * @throws Exception
	 */
	private void commitProcess(String taskId, Map<String, Object> variables, String activityId) throws Exception {
		if (variables == null) {
			variables = new HashMap<String, Object>();
		}
		// 跳转节点为空，默认提交操作
		if (StringUtils.isEmpty(activityId)) {
			taskService.complete(taskId, variables);
		} else {// 流程转向操作
			turnTransition(taskId, activityId, variables);
		}
	}

	/**
	 * 中止流程(特权人直接审批通过等)
	 * 
	 * @param taskId
	 */
	public void endProcess(String taskId, Map<String, Object> variables) throws Exception {
		ActivityImpl endActivity = findActivitiImpl(taskId, "end");
		commitProcess(taskId, variables, endActivity.getId());
	}

	/**
	 * 根据流入任务集合，查询最近一次的流入任务节点
	 * 
	 * @param processInstance
	 *            流程实例
	 * @param tempList
	 *            流入任务集合
	 * @return
	 */
	private ActivityImpl filterNewestActivity(ProcessInstance processInstance, List<ActivityImpl> tempList) {
		while (tempList.size() > 0) {
			ActivityImpl activity_1 = tempList.get(0);
			HistoricActivityInstance activityInstance_1 = findHistoricUserTask(processInstance, activity_1.getId());
			if (activityInstance_1 == null) {
				tempList.remove(activity_1);
				continue;
			}

			if (tempList.size() > 1) {
				ActivityImpl activity_2 = tempList.get(1);
				HistoricActivityInstance activityInstance_2 = findHistoricUserTask(processInstance, activity_2.getId());
				if (activityInstance_2 == null) {
					tempList.remove(activity_2);
					continue;
				}

				if (activityInstance_1.getEndTime().before(activityInstance_2.getEndTime())) {
					tempList.remove(activity_1);
				} else {
					tempList.remove(activity_2);
				}
			} else {
				break;
			}
		}
		if (tempList.size() > 0) {
			return tempList.get(0);
		}
		return null;
	}

	/**
	 * 根据任务ID和节点ID获取活动节点 <br>
	 * 
	 * @param taskId
	 *            任务ID
	 * @param activityId
	 *            活动节点ID <br>
	 *            如果为null或""，则默认查询当前活动节点 <br>
	 *            如果为"end"，则查询结束节点 <br>
	 * 
	 * @return
	 * @throws Exception
	 */
	private ActivityImpl findActivitiImpl(String taskId, String activityId) throws Exception {
		// 取得流程定义
		ProcessDefinitionEntity processDefinition = findProcessDefinitionEntityByTaskId(taskId);

		// 获取当前活动节点ID
		if (StringUtils.isEmpty(activityId)) {
			activityId = findTaskById(taskId).getTaskDefinitionKey();
		}

		// 根据流程定义，获取该流程实例的结束节点
		if (activityId.toUpperCase().equals("END")) {
			for (ActivityImpl activityImpl : processDefinition.getActivities()) {
				List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
				if (pvmTransitionList.isEmpty()) {
					return activityImpl;
				}
			}
		}

		// 根据节点ID，获取对应的活动节点
		ActivityImpl activityImpl = ((ProcessDefinitionImpl) processDefinition).findActivity(activityId);

		return activityImpl;
	}

	/**
	 * 根据当前任务ID，查询可以驳回的任务节点
	 * 
	 * @param taskId
	 *            当前任务ID
	 */
	public List<ActivityImpl> findBackAvtivity(String taskId) throws Exception {
		List<ActivityImpl> rtnList = iteratorBackActivity(taskId, findActivitiImpl(taskId, null),
				new ArrayList<ActivityImpl>(), new ArrayList<ActivityImpl>());
		return reverList(rtnList);
	}

	/**
	 * 查询指定任务节点的最新记录
	 * 
	 * @param processInstance
	 *            流程实例
	 * @param activityId
	 * @return
	 */
	private HistoricActivityInstance findHistoricUserTask(ProcessInstance processInstance, String activityId) {
		HistoricActivityInstance rtnVal = null;
		// 查询当前流程实例审批结束的历史节点
		List<HistoricActivityInstance> historicActivityInstances = historyService.createHistoricActivityInstanceQuery()
				.activityType("userTask").processInstanceId(processInstance.getId()).activityId(activityId).finished()
				.orderByHistoricActivityInstanceEndTime().desc().list();
		if (historicActivityInstances.size() > 0) {
			rtnVal = historicActivityInstances.get(0);
		}

		return rtnVal;
	}

	/**
	 * 根据当前节点，查询输出流向是否为并行终点，如果为并行终点，则拼装对应的并行起点ID
	 * 
	 * @param activityImpl
	 *            当前节点
	 * @return
	 */
	private String findParallelGatewayId(ActivityImpl activityImpl) {
		List<PvmTransition> incomingTransitions = activityImpl.getOutgoingTransitions();
		for (PvmTransition pvmTransition : incomingTransitions) {
			TransitionImpl transitionImpl = (TransitionImpl) pvmTransition;
			activityImpl = transitionImpl.getDestination();
			String type = (String) activityImpl.getProperty("type");
			if ("parallelGateway".equals(type)) {// 并行路线
				String gatewayId = activityImpl.getId();
				String gatewayType = gatewayId.substring(gatewayId.lastIndexOf("_") + 1);
				if ("END".equals(gatewayType.toUpperCase())) {
					return gatewayId.substring(0, gatewayId.lastIndexOf("_")) + "_start";
				}
			}
		}
		return null;
	}

	/**
	 * 根据任务ID获取流程定义
	 * 
	 * @param taskId
	 *            任务ID
	 * @return
	 * @throws Exception
	 */
	public ProcessDefinitionEntity findProcessDefinitionEntityByTaskId(String taskId) throws Exception {
		// 取得流程定义
		ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
				.getDeployedProcessDefinition(findTaskById(taskId).getProcessDefinitionId());

		if (processDefinition == null) {
			throw new Exception("流程定义未找到!");
		}

		return processDefinition;
	}

	/**
	 * 根据任务ID获取对应的流程实例
	 * 
	 * @param taskId
	 *            任务ID
	 * @return
	 * @throws Exception
	 */
	public ProcessInstance findProcessInstanceByTaskId(String taskId) throws Exception {
		// 找到流程实例
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
				.processInstanceId(findTaskById(taskId).getProcessInstanceId()).singleResult();
		if (processInstance == null) {
			throw new Exception("流程实例未找到!");
		}
		return processInstance;
	}

	/**
	 * 根据任务ID获得任务实例
	 * 
	 * @param taskId
	 *            任务ID
	 * @return
	 * @throws Exception
	 */
	private TaskEntity findTaskById(String taskId) throws Exception {
		TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(taskId).singleResult();
		if (task == null) {
			throw new Exception("任务实例未找到!");
		}
		return task;
	}

	/**
	 * 根据流程实例ID和任务key值查询所有同级任务集合
	 * 
	 * @param processInstanceId
	 * @param key
	 * @return
	 */
	private List<Task> findTaskListByKey(String processInstanceId, String key) {
		return taskService.createTaskQuery().processInstanceId(processInstanceId).taskDefinitionKey(key).list();
	}

	/**
	 * 迭代循环流程树结构，查询当前节点可驳回的任务节点
	 * 
	 * @param taskId
	 *            当前任务ID
	 * @param currActivity
	 *            当前活动节点
	 * @param rtnList
	 *            存储回退节点集合
	 * @param tempList
	 *            临时存储节点集合（存储一次迭代过程中的同级userTask节点）
	 * @return 回退节点集合
	 */
	private List<ActivityImpl> iteratorBackActivity(String taskId, ActivityImpl currActivity,
			List<ActivityImpl> rtnList, List<ActivityImpl> tempList) throws Exception {
		// 查询流程定义，生成流程树结构
		ProcessInstance processInstance = findProcessInstanceByTaskId(taskId);

		// 当前节点的流入来源
		List<PvmTransition> incomingTransitions = currActivity.getIncomingTransitions();
		// 条件分支节点集合，userTask节点遍历完毕，迭代遍历此集合，查询条件分支对应的userTask节点
		List<ActivityImpl> exclusiveGateways = new ArrayList<ActivityImpl>();
		// 并行节点集合，userTask节点遍历完毕，迭代遍历此集合，查询并行节点对应的userTask节点
		List<ActivityImpl> parallelGateways = new ArrayList<ActivityImpl>();
		// 遍历当前节点所有流入路径
		for (PvmTransition pvmTransition : incomingTransitions) {
			TransitionImpl transitionImpl = (TransitionImpl) pvmTransition;
			ActivityImpl activityImpl = transitionImpl.getSource();
			String type = (String) activityImpl.getProperty("type");
			/**
			 * 并行节点配置要求：<br>
			 * 必须成对出现，且要求分别配置节点ID为:XXX_start(开始)，XXX_end(结束)
			 */
			if ("parallelGateway".equals(type)) {// 并行路线
				String gatewayId = activityImpl.getId();
				String gatewayType = gatewayId.substring(gatewayId.lastIndexOf("_") + 1);
				if ("START".equals(gatewayType.toUpperCase())) {// 并行起点，停止递归
					return rtnList;
				} else {// 并行终点，临时存储此节点，本次循环结束，迭代集合，查询对应的userTask节点
					parallelGateways.add(activityImpl);
				}
			} else if ("startEvent".equals(type)) {// 开始节点，停止递归
				return rtnList;
			} else if ("userTask".equals(type)) {// 用户任务
				tempList.add(activityImpl);
			} else if ("exclusiveGateway".equals(type)) {// 分支路线，临时存储此节点，本次循环结束，迭代集合，查询对应的userTask节点
				currActivity = transitionImpl.getSource();
				exclusiveGateways.add(currActivity);
			}
		}

		/**
		 * 迭代条件分支集合，查询对应的userTask节点
		 */
		for (ActivityImpl activityImpl : exclusiveGateways) {
			iteratorBackActivity(taskId, activityImpl, rtnList, tempList);
		}

		/**
		 * 迭代并行集合，查询对应的userTask节点
		 */
		for (ActivityImpl activityImpl : parallelGateways) {
			iteratorBackActivity(taskId, activityImpl, rtnList, tempList);
		}

		/**
		 * 根据同级userTask集合，过滤最近发生的节点
		 */
		currActivity = filterNewestActivity(processInstance, tempList);
		if (currActivity != null) {
			// 查询当前节点的流向是否为并行终点，并获取并行起点ID
			String id = findParallelGatewayId(currActivity);
			if (StringUtils.isEmpty(id)) {// 并行起点ID为空，此节点流向不是并行终点，符合驳回条件，存储此节点
				rtnList.add(currActivity);
			} else {// 根据并行起点ID查询当前节点，然后迭代查询其对应的userTask任务节点
				currActivity = findActivitiImpl(taskId, id);
			}

			// 清空本次迭代临时集合
			tempList.clear();
			// 执行下次迭代
			iteratorBackActivity(taskId, currActivity, rtnList, tempList);
		}
		return rtnList;
	}

	/**
	 * 还原指定活动节点流向
	 * 
	 * @param activityImpl
	 *            活动节点
	 * @param oriPvmTransitionList
	 *            原有节点流向集合
	 */
	private void restoreTransition(ActivityImpl activityImpl, List<PvmTransition> oriPvmTransitionList) {
		// 清空现有流向
		List<PvmTransition> pvmTransitionList = activityImpl.getOutgoingTransitions();
		pvmTransitionList.clear();
		// 还原以前流向
		for (PvmTransition pvmTransition : oriPvmTransitionList) {
			pvmTransitionList.add(pvmTransition);
		}
	}

	/**
	 * 反向排序list集合，便于驳回节点按顺序显示
	 * 
	 * @param list
	 * @return
	 */
	private List<ActivityImpl> reverList(List<ActivityImpl> list) {
		List<ActivityImpl> rtnList = new ArrayList<ActivityImpl>();
		// 由于迭代出现重复数据，排除重复
		for (int i = list.size(); i > 0; i--) {
			if (!rtnList.contains(list.get(i - 1)))
				rtnList.add(list.get(i - 1));
		}
		return rtnList;
	}

	/**
	 * 转办流程
	 * 
	 * @param taskId
	 *            当前任务节点ID
	 * @param userCode
	 *            被转办人Code
	 */
	public void transferAssignee(String taskId, String userCode) {
		taskService.setAssignee(taskId, userCode);
	}

	/**
	 * 流程转向操作
	 * 
	 * @param taskId
	 *            当前任务ID
	 * @param activityId
	 *            目标节点任务ID
	 * @param variables
	 *            流程变量
	 * @throws Exception
	 */
	private void turnTransition(String taskId, String activityId, Map<String, Object> variables) throws Exception {
		// 当前节点
		ActivityImpl currActivity = findActivitiImpl(taskId, null);
		// 清空当前流向
		List<PvmTransition> oriPvmTransitionList = clearTransition(currActivity);

		// 创建新流向
		TransitionImpl newTransition = currActivity.createOutgoingTransition();
		// 目标节点
		ActivityImpl pointActivity = findActivitiImpl(taskId, activityId);
		// 设置新流向的目标节点
		newTransition.setDestination(pointActivity);

		// 执行转向任务
		taskService.complete(taskId, variables);
		// 删除目标节点新流入
		pointActivity.getIncomingTransitions().remove(newTransition);

		// 还原以前流向
		restoreTransition(currActivity, oriPvmTransitionList);
	}

	public InputStream getImageStream(String taskId) throws Exception {
		/*
		 * ProcessDefinitionEntity pde = findProcessDefinitionEntityByTaskId(taskId);
		 * InputStream imageStream = ProcessDiagramGenerator.generateDiagram( pde,
		 * "png", runtimeService.
		 * getActiveActivityIds(findProcessInstanceByTaskId(taskId).getId())); return
		 * imageStream;
		 */
		return null;
	}

	public boolean isCheckPass(String processInstanceId) {
		// 判断流程是否已结束
		/*
		 * HistoricProcessInstance historicProcessInstance =
		 * historyService.createHistoricProcessInstanceQuery
		 * ().processInstanceId(processInstanceId).singleResult();
		 * if(null==historicProcessInstance.getEndTime())return false;
		 */
		// 判断审批状态
		List<HistoricVariableInstance> variableList = historyService.createHistoricVariableInstanceQuery()
				.processInstanceId(processInstanceId).list();
		if (null == variableList || variableList.size() <= 0)
			return false;
		for (HistoricVariableInstance variable : variableList) {
			System.out.println("variableName:" + variable.getVariableName());
			if (variable.getVariableName().equals("processCheckStatus")) {
				// 审核通过
				if (variable.getValue().equals("0")) {
					return true;
				}
			}

		}
		return false;
	}

	public String getFormKey(String processDefinitionId) {
		String formKey = "";
		try {
			List<HistoricTaskInstance> htaskList = historyService.createHistoricTaskInstanceQuery()
					.processDefinitionId(processDefinitionId).list();
			if (null != htaskList && htaskList.size() > 0) {
				formKey = htaskList.get(0).getFormKey();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return formKey;

	}

	public String getFormKeyByInstanceId(String processInstanceId) {
		String formKey = "";
		try {
			List<HistoricTaskInstance> htaskList = historyService.createHistoricTaskInstanceQuery()
					.processInstanceId(processInstanceId).list();
			if (null != htaskList && htaskList.size() > 0) {
				formKey = htaskList.get(0).getFormKey();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return formKey;

	}

	// 根据流程定义ID获取第一个用户节点ID
	public String getFirstUserNodeId(String processDefinitionId) {
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
		List<Process> processList = bpmnModel.getProcesses();
		for (Process process : processList) {
			// 返回该流程的所有任务，事件
			Collection<FlowElement> feList = process.getFlowElements();
			StartEvent startEvent = null;
			// 查找开始节点
			for (FlowElement f : feList) {
				if (f instanceof StartEvent) {
					// 开始节点
					startEvent = (StartEvent) f;
				}
			}
			if (null == startEvent)
				return null;
			// 查找开始节点关联关系
			SequenceFlow sequenceFlow = null;
			for (FlowElement f : feList) {
				if (f instanceof SequenceFlow) {
					SequenceFlow rowSF = (SequenceFlow) f;
					if (startEvent.getId().equals(rowSF.getSourceRef())) {
						sequenceFlow = (SequenceFlow) f;
						break;
					}

				}
			}
			if (null == sequenceFlow)
				return null;
			// 查找第一个用户节点
			UserTask userTask = (UserTask) process.getFlowElement(sequenceFlow.getTargetRef());
			if (null == userTask)
				return null;
			return userTask.getId();
		}
		return null;
	}

	// 流程下一个用户节点
	public String getNextNodeId(String processInstanceId) {
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
				.processInstanceId(processInstanceId).singleResult();
		String activitiId = processInstance.getActivityId();
		String processDefinitionId = processInstance.getProcessDefinitionId();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
		List<Process> processList = bpmnModel.getProcesses();
		for (Process process : processList) {
			// 返回该流程的所有任务，事件
			Collection<FlowElement> feList = process.getFlowElements();
			for (FlowElement f : feList) {
				// 判断是否当前节点
				if (f.getId().equals(activitiId)) {
					List<SequenceFlow> sequenceFlowList = ((org.activiti.bpmn.model.UserTask) f).getOutgoingFlows();
					for (SequenceFlow sf : sequenceFlowList) {
						String targetRef = sf.getTargetRef();
						FlowElement ref = process.getFlowElement(targetRef);
						if (ref instanceof UserTask) {
							return ref.getId();
						}
					}
				}
			}
		}
		return null;
	}

	// 查询流程节点人员
	public List<String> getNodeUserId(Long merchantId, Long projectId, String processDefinitionId, String nodeId) {
		List<String> userIdList = new ArrayList<String>();
		NodeUserDto nodeUserDto = new NodeUserDto();
		if (null != merchantId) {
			nodeUserDto.setMerchantId(Long.valueOf(merchantId));
		}
		if (null != projectId) {
			nodeUserDto.setProjectId(projectId);
		}
		if (StringUtils.isNotBlank(processDefinitionId)) {
			nodeUserDto.setProcessDefinitionId(processDefinitionId);
		}

		if (StringUtils.isNotBlank(nodeId)) {
			nodeUserDto.setNodeId(nodeId);
		}
		nodeUserDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		ResponseList<NodeUser> nodeUserList = nodeUserServiceFacade.findByDto(nodeUserDto);
		if (nodeUserList.isSuccess() && null != nodeUserList.getEntity()) {
			NodeUser nodeUser = nodeUserList.getEntity().get(0);
			userIdList.add(String.valueOf(nodeUser.getUserId()));
		}
		return userIdList;
	}

	// 查询项目流程启动Key
	public String getProcessKey(Long merchantId, Long projectId, ProcessTypeEnums ptenums) {
		ProjectProcdefDto projectProcdefDto = new ProjectProcdefDto();
		projectProcdefDto.setMerchantId(merchantId);
		projectProcdefDto.setProjectId(projectId);
		projectProcdefDto.setProcType(ptenums.getNo());
		ResponseList<ProjectProcdef> list = projectProcdefServiceFacade.findByDto(projectProcdefDto);
		if (list.isSuccess() && null != list.getEntity() && list.getEntity().size() > 0) {
			return list.getEntity().get(0).getProcKey();
		}
		return "";
	}

	// 启动流程
	public String startProcessInstance(Long merchantId, Long projectId, String processDefinitionKey, String businessKey,
			Map<String, Object> variables) {
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
				.processDefinitionKey(processDefinitionKey).orderByProcessDefinitionVersion().desc().list().get(0);
		// 找到第一个节点

		String nodeId = getFirstUserNodeId(processDefinition.getId());
		if (null == variables) {
			variables = new HashMap<String, Object>();
		}
		variables.put("nextUserId", "");
		variables.put("processProjectId", projectId);
		// 查询节点人员
		List<String> userIdList = getNodeUserId(merchantId, projectId, /* processDefinition.getId() */null, nodeId);
		if (userIdList.size() > 0) {
			variables.put("nextUserId", userIdList.get(0));
		}
		// 启动流程
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey,
				variables);
		sendMessageServiceFacade.applyMessageSend(processInstance.getId(), nodeId, userIdList);

		//添加是否发送OA开关,因绿城OA调试系统确实,所以测试环境是否发送视情况而定
		if(pmoConfig.isSendOaMsg()){
			// 发送待办通知
			List<Task> taskList = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId())
					.taskDefinitionKey(nodeId).list();
			if (taskList != null && taskList.size() > 0) {
				User user = ShiroUtil.getCurrentUser();
				try {
					oaSendHttpMessageService.sendWaitMessage(taskList.get(0), processInstance, ShiroUtil.getCurrentUser(),
							new Long(userIdList.get(0)), taskList.get(0).getId(), processDefinition.getName());
				} catch (Exception ex) {
					logger.error("启动流程,发送OA代办异常", ex);
					//新增业务操作异常记录
					businessLogServiceFacade.saveExceptionLog(user, "启动流程,发送OA代办异常", processInstance.getId(), JSONObject.toJSONString(ex));
				}
			}
		}

		return processInstance.getId();
	}

	// 查询流程人员
	public List<User> getProcUserList(Long merchantId, Long projectId, String procInstId) {
		List<User> userList = new ArrayList<User>();
		ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
				.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
		if (null == processInstanceHistoryLog)
			return userList;
		ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
				.processDefinitionKey(processInstanceHistoryLog.getProcessDefinitionId()).singleResult();
		if (null == processDefinition)
			return userList;
		List<String> userIdList = getNodeUserId(merchantId, projectId, processDefinition.getId(), null);
		for (String userId : userIdList) {
			User user = new User();
			user.setId(Long.valueOf(userId));
			userList.add(user);
		}
		return userList;
	}

	// 检查流程节点人员是否已设置 如果未设置返回false，已设置返回true
	public boolean checkNodeUser(Long merchantId, Long projectId, String processDefinitionKey) {
		/*
		 * ProcessDefinition processDefinition = repositoryService
		 * .createProcessDefinitionQuery()
		 * .processDefinitionKey(processDefinitionKey).singleResult();
		 */
		List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery()
				.processDefinitionKey(processDefinitionKey).orderByProcessDefinitionVersion().desc().list();
		ProcessDefinition processDefinition = processDefinitionList.get(0);
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
		List<Process> processList = bpmnModel.getProcesses();
		for (Process process : processList) {
			// 返回该流程的所有任务，事件
			Collection<FlowElement> feList = process.getFlowElements();
			for (FlowElement f : feList) {
				if (f instanceof UserTask) {
					List<String> userIdList = getNodeUserId(merchantId, projectId, processDefinition.getId(),
							f.getId());
					if (null == userIdList || userIdList.size() == 0) {
						return false;
					}
				}
			}
		}
		return true;
	}

	public List<ProcessScheduleVo> getProcessScheduleList(Long merchantId, String processInstanceId) {
		List<ProcessScheduleVo> psList = new ArrayList<ProcessScheduleVo>();
		if (StringUtils.isBlank(processInstanceId)) {
			return psList;
		}
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
				.processInstanceId(processInstanceId).singleResult();
		if (null == historicProcessInstance)
			return psList;
		Date hpiEndTime = historicProcessInstance.getEndTime();

		List<FlowElement> feList = getDefinitionNodes(historicProcessInstance);
		List<ProcessScheduleVo> psvList = getAuditPassNodes(historicProcessInstance);
		if (null == hpiEndTime) {
			// 流程未结束
			for (FlowElement fe : feList) {
				ProcessScheduleVo findPSV = null;
				for (ProcessScheduleVo psv : psvList) {
					if (fe.getId().equals(psv.getId())) {
						findPSV = psv;
					}
				}
				if (null == findPSV) {
					findPSV = new ProcessScheduleVo();
					findPSV.setId(fe.getId());
					findPSV.setTaskName(fe.getName());
					findPSV.setIsFirst(false);
					findPSV.setIsLast(false);
					findPSV.setAuditorStatusName("待提交");
					findPSV.setIsFinish(false);
					if (fe instanceof EndEvent) {
						findPSV.setIsLast(true);
					} else if (fe instanceof StartEvent) {
						findPSV.setIsFirst(true);
					}
				}
				psList.add(findPSV);
			}
		} else {
			// 流程结束
			boolean isPass = isCheckPass(processInstanceId);
			if (isPass) {
				// 审核通过
				for (FlowElement fe : feList) {
					ProcessScheduleVo findPSV = null;
					for (ProcessScheduleVo psv : psvList) {
						if (fe.getId().equals(psv.getId())) {
							findPSV = psv;
						}
					}
					/*
					 * if (null == findPSV) { findPSV = new ProcessScheduleVo();
					 * findPSV.setId(fe.getId()); findPSV.setTaskName(fe.getName());
					 * findPSV.setIsFirst(false); findPSV.setIsLast(false);
					 * findPSV.setIsFinish(false); findPSV.setAuditorStatusName("待提交"); if (fe
					 * instanceof EndEvent) { findPSV.setIsLast(true); } else if (fe instanceof
					 * StartEvent) { findPSV.setIsFirst(true); } }
					 */
					psList.add(findPSV);
				}
			} else {
				// 审核不通过,流程节点会跳节点组装
				psList.addAll(psvList);
			}
		}

		return psList;
	}

	private List<FlowElement> getDefinitionNodes(HistoricProcessInstance historicProcessInstance) {
		List<FlowElement> list = new ArrayList<FlowElement>();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(historicProcessInstance.getProcessDefinitionId());
		List<Process> processList = bpmnModel.getProcesses();
		for (Process process : processList) {
			Collection<FlowElement> feList = process.getFlowElements();
			for (FlowElement f : feList) {
				if (f instanceof StartEvent || f instanceof UserTask || f instanceof EndEvent) {
					list.add(f);
				} else {
					continue;
				}

			}
		}
		return list;
	}

	private List<ProcessScheduleVo> getAuditPassNodes(HistoricProcessInstance historicProcessInstance) {
		List<ProcessScheduleVo> taskList = new ArrayList<ProcessScheduleVo>();
		String startUserId = historicProcessInstance.getStartUserId();
		List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
				.processInstanceId(historicProcessInstance.getId()).list();
		ProcessScheduleVo processScheduleVo = null;
		for (HistoricActivityInstance hai : list) {
			if (null == hai.getEndTime()) {
				continue;
			}
			String activityType = hai.getActivityType();
			processScheduleVo = new ProcessScheduleVo();
			processScheduleVo.setIsFinish(true);
			processScheduleVo.setId(hai.getActivityId());
			processScheduleVo.setTaskName(hai.getActivityName());
			processScheduleVo.setIsFirst(false);
			processScheduleVo.setIsLast(false);
			processScheduleVo.setAuditorTime(DateUtils.DateToString(hai.getEndTime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
			if (activityType.equals("startEvent")) {
				processScheduleVo.setTaskName("提交审核");
				processScheduleVo.setAuditorStatusName("提交");
				processScheduleVo.setIsFirst(true);
				UserDto ud = new UserDto();
				ud.setUserAccount(startUserId);
				ResponseList<User> userList = userServiceFacade.findByDto(ud);
				if (userList.isSuccess() && null != userList.getEntity()) {
					processScheduleVo.setAuditorName(userList.getEntity().get(0).getUserName());
				}
			} else if (activityType.equals("endEvent")) {
				processScheduleVo.setIsLast(true);
				processScheduleVo.setTaskName("流程结束");
				processScheduleVo.setAuditorStatusName("结束");
				processScheduleVo.setAuditorName("");
			} else {
				List<Comment> commentList = taskService.getTaskComments(hai.getTaskId());
				if (null != commentList && commentList.size() > 0) {
					String userAccount = commentList.get(0).getUserId();
					processScheduleVo.setMessage(commentList.get(0).getFullMessage());
					UserDto ud = new UserDto();
					ud.setUserAccount(userAccount);
					ResponseList<User> userList = userServiceFacade.findByDto(ud);
					if (userList.isSuccess() && null != userList.getEntity()) {
						processScheduleVo.setAuditorName(userList.getEntity().get(0).getUserName());
					}

				}
				List<HistoricVariableInstance> variableList = historyService.createHistoricVariableInstanceQuery()
						.taskId(hai.getTaskId()).list();
				String taskCheckStatusName = "待审核";
				if (null != variableList && variableList.size() > 0) {
					for (HistoricVariableInstance variable : variableList) {
						if (variable.getVariableName().equals("taskCheckStatus")) {
							taskCheckStatusName = variable.getValue().equals("0") ? "通过" : "驳回";
						}

					}
				}
				processScheduleVo.setAuditorStatusName(taskCheckStatusName);
			}
			taskList.add(processScheduleVo);
		}
		return taskList;
	}

}